package edu.cs.usask.ca.silver.plugin.rcp.pages.preferences;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

import edu.cs.usask.ca.silver.definitions.SystemProperties;
import edu.cs.usask.ca.silver.plugin.rcp.Activator;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverPreferenceEntries;
import edu.cs.usask.ca.silver.plugin.rcp.dao.SilverBusinessLogicController;

public class VensimPreferencePage extends FieldEditorPreferencePage implements
		IWorkbenchPreferencePage {

	public VensimPreferencePage() {
		super(GRID);
	}

	/**
	 * Create fields in the editor pane
	 */
	public void createFieldEditors() {
		if (SystemProperties.OS_NAME.startsWith("Windows")) {
			addField(new FileFieldEditor(
					SilverPreferenceEntries.VENDLL32.name(),
					SilverPreferenceEntries.VENDLL32
							.getLabelTextToBeDisplayed(), true,
					getFieldEditorParent()));
		}
	}

	/**
	 * Initialization
	 */
	public void init(IWorkbench workbench) {
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
		if (SystemProperties.OS_NAME.startsWith("Windows")) {
			setDescription("Please Specify the path to Vensim Dll (for example: C:\\dll\\VenDLL32.dll):");
		} else {
			setDescription("Based on our copy of Vensim, our Vensim support is limited to windows platform (due to the limitation of Vensim DLL from VenApp). If you have knowledge in getting VenApp working on mac, please let us know!");
		}
	}

	public boolean performOk() {

		boolean result = super.performOk();
		boolean loadDLL = false;
		String dllPath = SilverBusinessLogicController
				.getPreferenceEntry(SilverPreferenceEntries.VENDLL32);
		try {
			loadDLL = SilverBusinessLogicController.loadVensimDLL(dllPath);
		} catch (java.lang.UnsatisfiedLinkError e) {
			MessageDialog
					.openError(
							getShell(),
							"Unable to load Vensim DLL",
							"The file specfied is not a valid DLL library for this system.\nSILVER did not load Vensim DLL.\n Generally the Vensim DLL is named as VenDLL32.dll");
		}
		if (result && loadDLL) {
			MessageDialog
					.openInformation(
							getShell(),
							"Vensim DLL Status",
							"Vensim DLL is properly loaded to SILVER, you may now proceed to work on Vensim files.");
			return true;
		} else {
			return MessageDialog
					.openQuestion(
							getShell(),
							"Unable to load Vensim DLL",
							"SILVER is unable to find Vensim DLL from the specified path.\nVensim support is not loaded.\nWould you like to proceed?");

		}

	}
}
